<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- alert警告 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
      <!-- 商品分类级联选择器 -->
      <el-row>
        <el-col>
          选择商品分类:
          <el-cascader
            v-model="value"
            :options="goodsCateList"
            :props="{ expandTrigger: 'hover', label:'cat_name',value:'cat_id'}"
            @change="handleSelect"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisableBtn"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  class="input"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParmas(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisableBtn"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  class="input"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParmas(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      goodsCateList: [],
      //   级联选择器选中的商品id
      value: [],
      //   默认选中的tab标签页
      activeName: 'many',
      // 动态参数表格数据
      manyTableData: null,
      // 静态属性表格数据
      onlyTableData: null,
      // 对话框的显示与隐藏
      addDialogVisible: false,
      // 添加数据表单对象
      addForm: {
        attr_name: ''
      },
      // 添加数据规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '参数名称长度应在2~20个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 修改对话框的显示与隐藏
      editDialogVisible: false,
      // 修改数据表单对象
      editForm: {
        attr_name: '',
        attrId: ''
      },
      // 修改数据规则对象
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '参数名称长度应在2~20个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    // 获取所有的商品分类
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.goodsCateList = res.data
    },
    // 在级联选择器选项发生改变时触发该函数
    handleSelect() {
      this.getParamsData()
    },
    // tab栏被点击的时候触发
    handleClick() {
      this.getParamsData()
    },
    // 获取商品参数
    async getParamsData() {
      // 判断选中的是否为三级商品分类
      if (this.value.length !== 3) {
        this.value = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      // 如果是三级分类的话，那么发送http请求 获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        if (item.attr_vals) {
          item.attr_vals = item.attr_vals.split(' ')
        } else {
          item.attr_vals = []
        }
        // 控制输入框的显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭dialog对话框时重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 提交添加参数表单
    submitAddForm() {
      // 进行表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.getParamsData()
        this.addDialogVisible = false
        return this.$message.success(res.meta.msg)
      })
    },
    // 点击编辑按钮弹出对话框
    async edit(obj) {
      this.editForm.attrId = obj.attr_id
      this.editDialogVisible = true
      // 根据id查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${obj.attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('参数名称获取失败')
      }
      this.editForm.attr_name = res.data.attr_name
    },
    // 关闭修改对话框时重置表单对象
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改表单
    submitEditForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attrId}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success('编辑成功')
      })
    },
    // 删除参数
    delParmas(obj) {
      // 弹出询问框，询问管理用是否真的要删除该参数
      this.$confirm('您确定要永久删除该参数吗？', '提示', {
        confirmBottonText: '确定',
        cancelBottonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${obj.attr_id}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.getParamsData()
          return this.$message.success('删除成功')
        })
        .catch(() => {
          return this.$message.info('操作已取消')
        })
    },
    // 控制添加标签的显示与隐藏
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      //  如果用户输入的为有效值时
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      this.savaParams(row)
    },
    // 点击添加标签按钮显示输入框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick的作用是，当页面上的元素被重新渲染时，
      // 才会执行回调函数中的代码 当 row.inputVisible = true
      // 时，页面中的input元素还没有被渲染，所以需要使用$nextTick
      // 函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.savaParams(row)
    },
    // 保存用户更改的参数
    async savaParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    }
  },
  computed: {
    // 判断按钮是否应该为禁用状态
    isDisableBtn() {
      if (this.value.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 获取选中的三级分类的id
    cateId() {
      if (this.value.length === 3) {
        return this.value[2]
      }
      return null
    },
    // 添加属性对话框标题显示
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 20px 0;
}
.el-tag {
  margin: 0 5px;
}
.input {
  width: 100px;
}
</style>
